<?php 
namespace App\Http\Models;
use Illuminate\Database\Eloquent\Model;

class GameCodeModel extends Model
{
    const STATUS_DELETE = 0;
    const STATUS_EXCHANGED = 1;
    const STATUS_UNEXCHANGE = 2;
    const STATUS_RECEIVE = 3;

    protected $connection = 'db_main';
    protected $isSharding = 1;
    protected $table = 'wp_sdk_gamecode';

    protected $fillable = ['appid', 'lot_id', 'openid', 'gamecode', 'status'];

    public $timestamps = false;

    public static function import($appid, $lot_id, $lot_code_setting, $lot_count)
    {
        $codes = array();
        if(isset($lot_code_setting['type']) && $lot_code_setting['type'] == 1) {
            $lot_code_setting['prefix'] = isset($lot_code_setting['prefix']) ? $lot_code_setting['prefix'] : '';
            $codes = generate_nonce_number_array($lot_count, 6);
        } else if(isset($lot_code_setting['type']) && $lot_code_setting['type'] == 2) {
            if($lot_code_setting['key']) {
                $codes = GameCodeCacheModel::smembers($lot_code_setting['key']);
                GameCodeCacheModel::del($lot_code_setting['key']);
            }
        }

        if(!empty($codes)) {
            for ($i=0; $i < 20; $i++) { 
                $slice_codes = array_slice($codes, $i*5000, 5000);
                $insertRows = array();
                foreach ($slice_codes as $code) {
                    $insertRows[] = [
                        "appid" => $appid,
                        "lot_id" => $lot_id,
                        "openid" => '',
                        "gamecode" => $code,
                        "status" => self::STATUS_UNEXCHANGE
                    ];
                }
                self::create($insertRows);
            }
        }
    }

    /**
     * 删除一个奖品详情
     */
    public static function delGameCode($appid, $ids) {
        if(!$appid || !$ids) return false;
        $data = array(
            'status' => self::STATUS_DELETE
        );
        $map['appid'] = $appid;
        $map['status'] = array('NEQ', self::STATUS_DELETE);
        if (!is_array($ids)) {
            $ids = array($ids);
        }
        $map['lot_id'] = array('IN', $ids);
        self::where($map)->update($data);
    }

}